package com.wis.bolt.common;

import com.wis.TopologyDrive;
import com.wis.traffic.entity.dao.DataTimes;
import com.wis.traffic.post.service.DataTimesService;
import com.wis.traffic.post.service.impl.DataTimesServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Map;

/**
 * @Description: traffic_fan
 * @author: fan
 * @Date: Created in 2018/11/26 9:51
 * @Modified By:
 */
public class ZhuangDianSpiltBolt extends BaseRichBolt {
    private OutputCollector collector;
    private static String tmpId = new String();
    private static DataTimesService dataTimesService;
    private static String typeProduce;

    @Override
    public void prepare(Map map, TopologyContext context, OutputCollector collector) {
        this.collector = collector;
        dataTimesService = new DataTimesServiceImpl();
        typeProduce = map.get(TopologyDrive.TYPE_PRODUCE).toString();
    }

    @Override
    public void execute(Tuple tuple) {
        String key = tuple.getStringByField("key");
        String value = tuple.getStringByField("value");

        try {
            if (StringUtils.isNotBlank(value)) {
                String[] lines = value.split("_", 2);
                if ((StringUtils.isNotBlank(tmpId) && !tmpId.equals(lines[0]))) {
                    this.collector.emit(new Values(key, "over"));
                }
                tmpId = lines[0];
                this.collector.emit(new Values(key, value));
                String splitId = value.split(",", 2)[0];
                // if (splitId.equals("10_0")) {
                //     DataTimes dataTimes = new DataTimes();
                //     dataTimes.setProduct_type(Integer.parseInt(typeProduce));
                //     dataTimes.setUpdated_time_xj(key);
                //     dataTimesService.insertOrUpdate(dataTimes);
                // }
                if (splitId.contains("XA45_12")) {
                    this.collector.emit(new Values(key, "jies"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.collector.ack(tuple);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("key", "value"));
    }
}